//index.js
//获取应用实例
let md5 = require("../../utils/md5.js")
let axios = require("../../utils/util.js")
import {
  IMSDK,
} from '../../utils/common.js';
const app = getApp()
const myaudio = wx.createInnerAudioContext() //音频
Page({
  data: {
    deviceId: '',
    scrollLeft: 0,
    scrollViewWidth: 0,
    opacity: 0,
    Sum_: 0, //未读信息 
    innerAudioContext: '',
    choiceList: "", //精选列表
    recommendList: "", //推荐列表
    menu_list: [], //扩列开黑四条 
    recommendedStars: [], //推荐明星
    hot_room: [], //热门房间
    hot_room_v3: [], //推荐房间
    online_user_v3: [], //推荐明星列表
    adList_v3: [], //轮播图
    taglist_v3: [], //扩列标签
    list_v3: [], //扩列列表
    tabTitle_v3: [], //头部交友
    cur: "0", //筛选默认不限
    isrecommendedStars: false, //筛选是否显示
    isStart: null, //播放下标
    iscur: false, //播放状态
    page: "1",
    user_info: {}, //登录用户信息
    hasMore: true, //提示
    password: '', //密码
    input1: '',
    hiddenModal2: true,
    IM_login: false,
    messageTop: ["扩列", "派对"],
    mesChangeNum: 1,
    inter: '',
    // Deicon: 0,
    VajraDistrict: [],
    height_swiper: 0,
    huoliedome: false,
    curTab: 0,
    jiazaizhong: false,
  },
  async onReady() {  
    const deviceId = await app.globalData.SMSdk.getDeviceId();
    wx.setStorageSync('shumeiDeviceId', deviceId)
    wx.createSelectorQuery().select('.kuolie_tan').boundingClientRect((rect) => {
      this.data.scrollViewWidth = Math.round(rect.width)
    }).exec()
  },
  expandAll() {
    this.setData({
      huoliedome: !this.data.huoliedome
    })
  },
  changeType(data) {
    let room_id = data.currentTarget.dataset.room_id;
    let cid = data.currentTarget.dataset.cid;
    if (room_id == '0') {
      wx.navigateTo({
        url: '/pages/allRoom/allRoom?cid=' + cid,
      })
    } else {
      wx.navigateTo({
        url: '/pages/room/room?roomId=' + room_id,
      })
    }
  },
  preview(data) {
    let url = data.currentTarget.dataset.url;
    wx.navigateTo({
      url: '../link/link?url=' + url
    })
  },
  cur_list(data) {
    let index;
    index = data.currentTarget.dataset.index;
    let offsetLeft = data.currentTarget.offsetLeft;
    this.setData({
      jiazaizhong: false,
      curTab: index,
      page: 1,
      scrollLeft: offsetLeft - this.data.scrollViewWidth / 2
    })
    this.tab_iocn_title(index)
  },
  tab_iocn_title(gameid) {
    let params = {
      gameid: gameid,
      page: this.data.page,
    };
    axios.axios({
      url: "/chat/gangup",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          taglist_v3: res.data.result.gamelist,
          list_v3: res.data.result.list
        })
        this.height_swipers()
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  height_swipers() {
    let otherArr = ["background:linear-gradient(180deg, #D4FFDD,#E5FAFF)", "background: linear-gradient(180deg, #E2C5FF,#FBEBFF)", "background:linear-gradient(180deg, #FFFAC2,#D4FFFB)", "background:linear-gradient(180deg, #C4F1FF,#EAFFFA)"];
    let list_v3 = this.data.list_v3
    list_v3.forEach((item, index) => {
      item.game_bgcolor = otherArr[index % 4]
    })
    this.setData({
      list_v3: list_v3
    })
    let that = this;
    var query = wx.createSelectorQuery();
    query.select('.timu_list' + that.data.mesChangeNum).boundingClientRect(function (rect) {
      if (rect) {
        that.setData({
          // 获取要循环标签的高度 
          height_swiper: rect.height,
        })
      }
    }).exec();
  },
  // startInter: function () {
  //   var that = this;
  //   that.data.inter = setInterval(() => {
  //     that.data.Deicon++
  //     that.setData({
  //       Deicon: that.data.Deicon++
  //     })
  //     if (that.data.Deicon == this.data.tabTitle_v3.length) {
  //       that.setData({
  //         Deicon: 0
  //       })
  //     }
  //   }, 4500);
  // },
  switchTab: function (e) {
    this.mesChange(e.detail.current)
    this.height_swipers()
  },

  mesChange(data) {
    let index;
    data.currentTarget ? index = data.currentTarget.dataset.current : index = data;
    this.setData({
      mesChangeNum: index,
    })
    switch (index) {
      case 0:
        this.texpansioninfo()
        break;
      case 1:
        this.indexV3()
        break;
    }
  },

  //扩列交友tab
  texpansioninfo() {
    let params = {
      gameid: this.data.curTab,
      page: this.data.page,
    };
    axios.axios({
      url: "/chat/gangup",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          taglist_v3: res.data.result.gamelist,
          list_v3: res.data.result.list,
          jiazaizhong: false
        })
        this.height_swipers()
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  input1(e) {
    this.setData({
      input1: e.detail.value
    })
  },
  //语音播放
  start(data) { 
    let that = this;
    let e = data.currentTarget.dataset.start[0]; //播放地址
    console.log(e);
    let e2 = data.currentTarget.dataset.start[1]; //第几个下标
    that.setData({
      iscur: true
    })
    console.log(that.data.isStart);
    console.log(e2);
    if (that.data.isStart != e2) { //播放中
      console.log("播放");
      that.setData({
        isStart: e2
      })
      myaudio.src = e;
      myaudio.play(); //开始播放 
    } else { //暂停播放
      console.log("暂停");
      myaudio.pause()
    }
  },

  //全部房间
  toALLRoom() {
    this.setData({
      isrecommendedStars: !this.data.isrecommendedStars
    })
  },
  //扩列开黑
  tomenu_lists_image(data) {
    let event_index = data.currentTarget.dataset.type_id;
    console.log(event_index);
    wx.navigateTo({
      url: '/pages/allRoom/allRoom?type_id=' + event_index,
    })
  },
  //热门房间
  toHotRoom() {
    wx.navigateTo({
      url: '/pages/allRoom/allRoom',
    })
  },

  //搜索
  tosearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  roomList() {
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
    };
    axios.axios({
      url: "/index/index_v2",
      data: params
    }).then((res) => {
      this.setData({
        menu_list: res.data.result.menu_list,
        hot_room: res.data.result.hot_room
      })
      let newtime = (Date.parse(new Date())).toString();
      wx.setStorageSync('newtime', res.data.result.newtime - newtime)
    })
  },
  //点击头像和名字去个人主页
  toperson(data) {
    wx.navigateTo({
      url: '/pages/me/me?memberId=' + data.currentTarget.dataset.memberid,
    })
  },
  //点击头像和名字去个人主页
  toroom_link(data) {
    let roomid = data.currentTarget.dataset.memberid;
    wx.navigateTo({
      url: '/pages/room/room?roomId=' + roomid,
    })
    // this.joinRoom()
  },
  //加入房间
  joinRoom(password) {
    let params = {
      roomId: this.data.roomid,
      password: password,
      userId: app.globalData.user_id.toString(),
      token: app.globalData.userToken,
      shumeiDeviceId: wx.getStorageSync('shumeiDeviceId'),
      clientId: wx.getStorageSync('getClientId')
    };
    axios.axios({
      url: "/chat/joinRoom",
      data: params
    }).then((res) => {
      if (res.data.status == 0) { //加入房间是否有密码
        this.setData({
          hiddenModal2: true
        })
        wx.navigateTo({
          url: '/pages/room/room?roomId=' + this.data.roomid + '&password=' + this.data.password,
        })
      } else if (res.data.status == 101) {
        if (this.data.hiddenModal2) {
          this.setData({
            hiddenModal2: false
          })
        } else {
          return wx.showToast({
            title: res.data.text,
            icon: 'none',
            duration: 2000 //持续的时间
          })
        }
      } else {
        return wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  //Hi去聊天
  to_messageinfo(data) {
    let hi = data.currentTarget.dataset.hi
    console.log(hi);
    let datas = JSON.stringify(hi)
    console.log(datas);
    // wx.navigateTo({
    //   url: '/pages/messageInfo/messageInfo?index=' + encodeURIComponent(datas),
    // })
    wx.navigateTo({
      url: '/pages/messageInfo/messageInfo?Hi=' + encodeURIComponent(datas),
    })
  },
  //点击去找她
  goroom_in(data) {
    let event_index = data.currentTarget.dataset.type_id;
    wx.navigateTo({
      url: '/pages/room/room?roomId=' + event_index,
    })
  },
  recommendedStars_s(e) {
    let data;
    if (e) {
      data = e.currentTarget.dataset.recommendedstars.toString()
      this.setData({
        cur: data,
        page: 1
      })
    } else {
      data = 0;
      this.setData({
        cur: data
      })
    }
    var that = this;
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      sex: this.data.cur,
      page: this.data.page,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      sex: this.data.cur,
      page: this.data.page,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/index/recommendedStars",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        that.setData({
          online_user_v3: res.data.result, //加载数据
          isrecommendedStars: false,
        })
        this.height_swipers()
        wx.stopPullDownRefresh(); //停止当前页面下拉刷新
        return wx.showToast({
          title: "加载成功",
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //推荐明星
  recommendedStars(e) {
    let data;
    if (e) {
      data = e.currentTarget.dataset.recommendedstars.toString()
      console.log(e.currentTarget.dataset.recommendedstars);
      this.setData({
        cur: data
      })
    }
    var that = this;
    //页面累加
    var p = ++that.data.page;
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      sex: this.data.cur,
      page: this.data.page,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      sex: this.data.cur,
      page: this.data.page,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/index/recommendedStars",
      data: params
    }).then((res) => {
      //判断是否为空
      if (res.data.result.length != 0) {
        //把新加载的数据追加到原有的数组
        that.setData({
          online_user_v3: that.data.online_user_v3.concat(res.data.result), //加载数据
          page: p,
          hasMore: true,
        })
        this.height_swipers()
      } else {
        that.setData({
          hasMore: false
        })
        let timer
        clearTimeout(timer)
        timer = setTimeout(() => { //设置延迟执行
          that.setData({
            jiazaizhong: false,
          })
        }, 2000);
      }
    })
  },
  watch: function (ctx, obj) {
    Object.keys(obj).forEach(key => {
      this.observer(ctx.data, key, ctx.data[key], function (value) {
        obj[key].call(ctx, value)
      })
    })
  },
  // 监听属性，并执行监听函数
  observer: function (data, key, val, fn) {
    Object.defineProperty(data, key, {
      configurable: true,
      enumerable: true,
      get: function () {
        return val
      },
      set: function (newVal) {
        if (newVal === val) return
        fn && fn(newVal)
        val = newVal
      },
    })
  },
  login_IM() { 
    let tim;
    let that = this;
    tim = IMSDK(that)
    let userID = wx.getStorageSync("UserInformation").perfectNumber.toString()
    let userSig = wx.getStorageSync("UserInformation").tokenNew
    // 开始登录
    let promise = tim.login({
      userID,
      userSig
    });
    promise.then(function (imResponse) {
      console.log("IM登录成功"); // 登录成功
      // console.log("IM登录成功:", imResponse.data); // 登录成功
      if (imResponse.data.repeatLogin === true) {
        // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
        console.log("IM重复登录:", imResponse.data.errorInfo);
      }
    }).catch(function (imError) {
      // console.warn('IM登录失败'); // 登录失败的相关信息 
      console.warn('IM登录失败:', imError); // 登录失败的相关信息 
      // wx.clearStorage()
      wx.showToast({
        title: imError,
        icon:"none",
        duration:3000
      })
      setTimeout(()=>{
        wx.reLaunch({
          url: '/pages/login/login',
        })
      },3000)
    });
  },
  indexV3() {
    let params = {};
    axios.axios({
      url: "/index/indexV3",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          hot_room_v3: res.data.result.hot_room, //推荐房间
          online_user_v3: res.data.result.online_user, //推荐房间
          adList_v3: res.data.result.adList, //轮播图
          tabTitle_v3: res.data.result.menu_list
        })
        let newtime = (Date.parse(new Date())).toString();
        wx.setStorageSync('newtime', res.data.result.newtime - newtime)
        this.height_swipers()
        // clearInterval(this.data.inter)
        // this.startInter()
      }
    })
  },

  onPageScroll: function (e) {
    if (60 < e.scrollTop && e.scrollTop < 150) {
      this.setData({
        opacity: e.scrollTop * 0.006
      })
      this.getTabBar().tab_icon(0);
    } else if (e.scrollTop > 150) {
      this.setData({
        opacity: 1
      })
      this.getTabBar().tab_icon(1);
    } else {
      this.setData({
        opacity: 0
      })
      this.getTabBar().tab_icon(0);
    }
  },

  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    setTimeout(() => {
      let user_list = wx.getStorageSync('UserInformation')
      if (user_list) {
        this.setData({ 
          user_info: user_list
        })
        this.indexV3()
        // this.roomList()
      }
    }, 2500)
  },
  onLoad() {
    let that = this;
    myaudio.onPlay(() => { //开始播放
      console.log("开始的回调");
    })
    myaudio.onPause((res) => { //暂停播放
      console.log('暂停播放回调!');
      that.setData({
        isStart: null
      })
    })
    myaudio.onEnded((res) => { //结束播放
      console.log("结束的回调");
      that.setData({
        isStart: null,
        iscur: false
      })
      // myaudio.stop()
    })
    this.getOPenid()
    let user_list = wx.getStorageSync('UserInformation')
    if (user_list) {
      app.globalData.userInfo = user_list
      app.globalData.user_id = user_list.userId;
      app.globalData.userToken = user_list.token;
      app.globalData.perfectNumber = user_list.perfectNumber;
      this.setData({
        user_info: user_list
      })
      this.indexV3()
      this.login_IM()


    } else { 
      this.code_userlist()
    }
    const path = wx.getStorageSync('Room_image')
    if (!path) { //判断是否有缓存，有直接用缓存，没有就用线上的并加入房间缓存
      let Room_image = {};
      wx.setStorageSync('Room_image', Room_image);
    }
  },
  code_userlist() {
    let promise = new Promise((resolve, reject) => {
      let _ = this;
      wx.login({ //获取code
        success: res => {
          let params = {
            code: res.code,
          };
          axios.axios({
            url: "/user/appletLogin",
            data: params
          }).then((res) => {
            resolve(res.data.result)
          })
        }
      });
    })
    promise.then((res) => {
      wx.setStorageSync('UserInformation', res)
      app.globalData.user_id = res.userId;
      app.globalData.userToken = res.token;
      app.globalData.perfectNumber = res.perfectNumber;
      this.indexV3()
      this.login_IM()
    })
  },
  getOPenid() { 
    let _ = this;
    wx.login({ //获取code
      success: res => {
        let params = {
          code: res.code,
          type: "2",
        };
        axios.axios({
          url: "/index/getOpenId",
          data: params
        }).then((res) => {
          app.globalData.openid = res.data.result.openid;
          app.globalData.unionid = res.data.result.unionid;
          wx.setStorageSync('unionid', res.data.result.unionid)
        })
      }
    });
  },
  errorfn(e){
    console.log(e);
  },
  // 去排行榜
  to_finding() {
    wx.navigateTo({
      url: '/pages/finding/finding',
    })
  },
  drop_down_gangup() {
    let _ = this;
    var p = ++_.data.page;
    let params = {
      gameid: _.data.curTab,
      page: p,
    };
    axios.axios({
      url: "/chat/gangup",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        if (res.data.result.list.length != 0) {
          _.setData({
            page: p,
            list_v3: _.data.list_v3.concat(res.data.result.list),
            hasMore: true,
          })
          _.height_swipers()
        } else {
          _.setData({
            hasMore: false
          })
          let timer
          clearTimeout(timer)
          timer = setTimeout(() => { //设置延迟执行
            _.setData({
              jiazaizhong: false,
            })
          }, 3000);
        }
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  onReachBottom() {
    this.setData({
      jiazaizhong: true
    })
    if (this.data.mesChangeNum == '1') {
      //派对下拉加载更多
      console.log("派对下拉加载更多");
      this.recommendedStars()
    } else {
      //扩列下拉加载更多
      this.drop_down_gangup()
    }
  },
  onPullDownRefresh() {
    this.indexV3()
    this.setData({
      page: '1',
      sex: '0',
    })
    this.recommendedStars_s()
  },
})
